package com.tanhua.app.Service;

import cn.hutool.core.util.RandomUtil;
import com.tanhua.api.UserApi;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.User;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @DubboReference
    private UserApi userApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    MqMessageService mqMessageService;

    public void sendMessage(String phone){
       /* String code = RandomStringUtils.randomNumeric(6);*/
String code ="123456";
      /*  smsTemplate.sendSms(phone,code);*/
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));
    }


    public Map loginVerification(String mobile ,String code){
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + mobile);
        if (redisCode == null||!redisCode.equals(code)) {
            throw new RuntimeException("验证码或手机号错误");
        }
        User user = userApi.findByMobile(mobile);
        boolean isNew=false;
        String type = "0101";  //登录
        if(user == null){
             user = new User();
            user.setMobile(mobile);
            user.setPassword("123456");
            Long userid = userApi.save(user);
            user.setId(userid);
            isNew = true;

            Boolean aBoolean = huanXinTemplate.createUser(Constants.HX_USER_PREFIX + userid, Constants.INIT_PASSWORD);
            if (aBoolean){
                user.setHxUser(Constants.HX_USER_PREFIX + userid);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.updateById(user);
            }

        }

     Map<String,Object>  tokenMap = new HashedMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", mobile);
        String token = JwtUtils.getToken(tokenMap);

        HashedMap map = new HashedMap();
        map.put("token",token);
        map.put("isNew",isNew);

mqMessageService.sendLogMessage(user.getId(),type,"user","");
        return map;
    }
}
